#!/bin/bash

running=`ps -e | grep netcheckfix | wc -l`
if [ $running -gt 2 ]; then 
	echo "Already running, counted $running processes"	
	exit 0
fi

exec_path=/home/pi/siweather/scripts
log_file=/home/pi/logs/netcheckfix_log

sierra=`lsusb | grep "Sierra Wireless"`
zte=`lsusb | grep "ONDA Communication"`

if [ -z "$sierra" -a -z "$zte" ]; then
	echo "On "`date`", no 3G device was present, ran 'netrestart'" >> $log_file
	sudo $exec_path/netrestart &
	exit 0
fi

ppp=`sudo $exec_path/pppcheck`


if [ "$ppp" = "no" ]; then
	sleep 5
	ppp=`sudo $exec_path/pppcheck`
	if [ "$ppp" = "no" ]; then
		sudo killall netrestart
		sudo killall wvdial
		sudo $exec_path/netrestart &
		echo "On "`date`" the 'PPP' interface check failed, ran 'netrestart'" >> $log_file
		exit 0
	fi
fi

IP_LOCAL=`sudo $exec_path/getip`
IP_NOIP2=`sudo noip2 -S 2>&1 | grep "Last IP Address set" | awk '{print $NF}'`

DNS_LOOKUP=`host siweather.no-ip.org`
IP_DNS=`echo $DNS_LOOKUP | awk '{print $NF}'`
NO_CONNECTION=`echo $DNS_LOOKUP | grep "timed out"`

if [ -n "$NO_CONNECTION" ]; then
	sudo $exec_path/netrestart &
	echo "On "`date`" could not talk to DNS, ran 'netrestart'" >> $log_file
	exit 0
fi

if [ ! "$IP_LOCAL" = "$IP_DNS" ]; then
	if [ ! "$IP_LOCAL" = "$IP_NOIP2" ]; then
		sudo noip2 -i "$IP"
		echo "On "`date`" the IP address in no-ip.com was incorrect, updated" >> $log_file
		exit 0
	else
		echo "On "`date`" the DNS server held the wrong IP, nothing we can do" >> $log_file
		exit 0
	fi
fi

# Connection seems fine, if the internet isn't working check the DNS servers (/etc/resolv.conf and /etc/ppp/resolv.conf), they should contain something like "nameserver 202.27.158.40"
sleep 1

exit 0
